var __brzl_tryLoginState = 'trying';

var __brzl_tryLogin = function() {
    for (var i = 0; i < document.forms.length; i++) {
        var form = document.forms[i];
        if (form.method != 'post') {
            continue;
        }
        var usernameField = undefined;
        var passwordField = undefined;
        for (var j = 0; j < form.elements.length; j++) {
            var field = form.elements[j];
            if (field.type == 'text' || field.type == 'email') {
                if (!usernameField) {
                    usernameField = field;
                } else {
                    usernameField = undefined;
                    break;
                }
            } else if (field.type == 'password') {
                if (!passwordField) {
                    passwordField = field;
                } else {
                    passwordField = undefined;
                    break;
                }
            } else if (field.type == 'textarea') {
                usernameField = undefined;
                passwordField = undefined;
                break;
            }
        }
        if (usernameField && passwordField) {
            usernameField.value = {{username|json}};
            passwordField.value = {{password|json}};
            console.log('submitting username=' + usernameField.value
                        + ' password=*** to detected login form');
            try {
                form.submit();
            } catch (e) {
                // "If a form control (such as a submit button) has a name or
                // id of 'submit' it will mask the form's submit method." -MDN
                // http://stackoverflow.com/a/2000021
                var pseudoForm = document.createElement('form');
                pseudoForm.submit.apply(form);
            }
            __brzl_tryLoginState = 'submitted-form';
            return;
        }
    }
    __brzl_tryLoginState = 'login-form-not-found';
};

__brzl_tryLogin();
